<?php


namespace app\wechat\controller;


use app\common\controller\WechatBase;
use app\common\model\ShopCash;
use app\common\model\ShopMoneyLog;
use app\common\model\UserCash;
use EasyWeChat\Factory;
use think\Db;

class CallBack extends WechatBase
{
//    支付回调
    public function payCallBack(){
        trace('微信支付回调', 'notice');
        $testxml = file_get_contents("php://input");
        $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
        $result = json_decode($jsonxml, true);//转成数组，
        trace($result, 'notice');
        if ($result) {
            //如果成功返回了
            $out_trade_no = $result['out_trade_no'];
            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {

                $order = Db::name('Order')->where('order_sn', '=', $out_trade_no)->find();

                $update = ['pay_status' => 20, 'order_status' => 30, 'pay_time' => date('Y-m-d H:i:s')];

                if ($order['is_add_sale_num'] == 0) {

                    $update['is_add_sale_num'] = $order['num'];

//                增加销量
                    if (!empty($order['goods_id'])) {
                        Db::name('goods')->where('id', '=', $order['goods_id'])->setInc('sale_num', $order['num']);
                        Db::name('goods')->where('id', '=', $order['goods_id'])->setInc('sale_num_xu', $order['num']);
                    }
//                    减去对应规格的库存
                    Db::name('goodsFormat')->where('id','=',$order['sku_id'])->setDec('stock',$order['num']);
                }
//            改变订单状态
                Db::name('Order')->where('order_sn', '=', $out_trade_no)->update($update);
            }
        }
    }

//    核销二维码
    public function checkTicket(){
        $param = input();
        return redirect(url('store/index',[],'',true).'?order_id='.$param['order_id']);
    }

//    店铺提现回调
    public function payCallbackCash()
    {
        trace('提现回调', 'notice');
        $testxml = file_get_contents("php://input");
        $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
        $result = json_decode($jsonxml, true);//转成数组，
        trace($result, 'notice');
        if ($result) {
            //如果成功返回了
            $out_trade_no = $result['out_trade_no'];
            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            }
        }
    }

//    用户提现回调
    public function payCallbackUserCash()
    {
        trace('用户提现回调', 'notice');
        $testxml = file_get_contents("php://input");
        $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
        $result = json_decode($jsonxml, true);//转成数组，
        trace($result, 'notice');
        if ($result) {
            //如果成功返回了
            $out_trade_no = $result['out_trade_no'];
            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            }
        }
    }

//    同意店铺提现申请记录
    public function passCash($id){
        $cash = ShopCash::where('id','=',$id)->find();
        if ($cash['state'] != 10){
            $this->error("当前记录已经被处理了，处理结果：".$cash['state']);
        }

        $shop = \app\common\model\Shop::where('id','=',$cash['shop_id'])->find();
        $user = \app\common\model\User::where('id','=',$shop['user_id'])->find();

        $partner_trade_no = empty($cash['partner_trade_no'])?date('YmdHis').$shop['id'].$user['id']:$cash['partner_trade_no'];

        ShopCash::editPost(['partner_trade_no'=>$partner_trade_no],['id'=>$cash['id']]);

        $wechat = config('wechat.');

        $wechat['notify_url'] = \think\facade\Request::domain().'/api/'.url('/wechat_login/payCallbackCash');

        $app = Factory::payment(config('wechat.'));
        $res = $app->transfer->toBalance([
            'partner_trade_no' => $partner_trade_no, // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
            'openid' => $user['openid'],
            'check_name' => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
            're_user_name' => '', // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
            'amount' => $cash['money']*100, // 企业付款金额，单位为分
            'desc' => '余额提现', // 企业付款操作说明信息。必填
        ]);
        trace('余额提现','notice');
        trace($res,'notice');

        if ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
            ShopCash::editPost(['state'=>20],['id'=>$cash['id']]);
            Db::name('shop')->where('id','=',$cash['shop_id'])->setDec('money',$cash['money']);
            ShopMoneyLog::create([
                'shop_id'=>$shop['id'],
                'before'=>$shop['money'],
                'value'=>$cash['money'],
                'after'=>Db::name('shop')->where('id','=',$cash['shop_id'])->value('money'),
                'remark'=>'手动申请提现',
                'type'=>'dec'
            ]);
        }
    }

//    同意用户提现
    public function passUserCash($id){
        $cash = UserCash::where('id','=',$id)->find();
        if ($cash['state'] != 10){
            $this->error("当前记录已经被处理了，处理结果：".$cash['state']);
        }

        $user = \app\common\model\User::where('id','=',$cash['user_id'])->find();

        $partner_trade_no = empty($cash['partner_trade_no'])?date('YmdHis').$user['id']:$cash['partner_trade_no'];

        ShopCash::editPost(['partner_trade_no'=>$partner_trade_no],['id'=>$cash['id']]);

        $wechat = config('wechat.');

        $wechat['notify_url'] = \think\facade\Request::domain().'/api/'.url('/wechat_login/payCallbackUserCash');

        $app = Factory::payment(config('wechat.'));
        $res = $app->transfer->toBalance([
            'partner_trade_no' => $partner_trade_no, // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
            'openid' => $user['openid'],
            'check_name' => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
            're_user_name' => '', // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
            'amount' => $cash['money']*100, // 企业付款金额，单位为分
            'desc' => '余额提现', // 企业付款操作说明信息。必填
        ]);
        trace('余额提现','notice');
        trace($res,'notice');

        if ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
            UserCash::editPost(['state'=>20],['id'=>$cash['id']]);
            Db::name('user')->where('id','=',$user['id'])->setDec('money',$cash['money']);
            ShopMoneyLog::create([
                'user_id'=>$user['id'],
                'before'=>$user['money'],
                'value'=>$cash['money'],
                'after'=>Db::name('user')->where('id','=',$user['id'])->value('money'),
                'remark'=>'手动申请提现',
                'type'=>'dec'
            ]);
        }
    }
}
